package com.example.commons.exception;

import com.example.commons.response.ResponseResult;
import com.example.commons.response.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BusinessAdvice {

    @ExceptionHandler(value = Exception.class)
    public ResponseResult handle(Exception ex) {
//        ex.printStackTrace();
        PrintStackTrace.error(ex);
        ResponseResult response = new ResponseResult();
        response.setCode(ResultCode.FAIL);
        response.setMsg(ex.getMessage().substring(ex.getMessage().indexOf(":")+1).trim());
        return response;
    }


    public static String extractChinese(String input) {
        String chineseText = input.replaceAll("[^\\u4e00-\\u9fa5]", "");
        return chineseText;
    }

    /**
     * SQLIntegrityConstraintViolationException是DataAccessException子类，
     * 如果使用ExceptionHandler(SQLIntegrityConstraintViolationException.class)，会捕获不到异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = DataAccessException.class)
    public ResponseResult handle(SQLIntegrityConstraintViolationException ex) {
        ResponseResult response = new ResponseResult();
        response.setCode(ResultCode.ERROR);
        PrintStackTrace.error(ex);
        if (ex.getMessage().contains("Duplicate entry")) {
            String s = ex.getMessage().split(" ")[2];
            s = s + " 已存在";
            response.setMsg(s);
            return response;
        }
        response.setMsg("未知错误");
        return response;
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult handle(BusinessException ex) {
        ResponseResult response = new ResponseResult();
        response.setCode(ResultCode.FAIL);
        response.setMsg(ex.getMessage());
        return response;
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    public ResponseResult handle(AccessDeniedException ex) {
        ResponseResult response = new ResponseResult();
        response.setCode(ResultCode.NO_AUTH);
        response.setMsg("无操作权限");
        return response;
    }

}
